<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
    <el-row :gutter="1">
      <el-col :span="6">
        <el-form-item label="材料编号" prop="matNo" >
          <el-input
            v-model="queryParams.matNo"
            placeholder="请输入材料编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="材料名称" prop="matName" >
          <el-input
            v-model="queryParams.matName"
            placeholder="请输入材料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
          <el-form-item label="实验时间">
            <el-date-picker
              v-model="daterangeCreateTime"
              
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
    </el-row>
    <!-- <el-row :gutter="1">
      <el-col :span="12">
        <el-form-item label="查询参数" prop="vjson">
          <el-input
            v-model="queryParams.vjson"
            placeholder="请输入材料名称"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 200%"
          />
        </el-form-item>
        
      </el-col>
    </el-row>   -->
    <el-row :gutter="1">
      <el-col :span="12">
        <el-form-item label="查询参数" prop="vjson">
          <search-condition :value="vjsonq"></search-condition>
        </el-form-item>
      </el-col>
    </el-row>  
    <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hustmed:material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hustmed:material:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hustmed:material:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="addTemplate"
          v-hasPermi="['hustmed:material:edit']"
        >新增模版</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" label="序号"></el-table-column>
      <!-- <el-table-column label="材料id" align="center" prop="id" /> -->
      <el-table-column label="材料名称" align="center" prop="matName" />
      <el-table-column label="材料编号" align="center" prop="matNo" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user" :value="scope.row.createBy"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user" :value="scope.row.updateBy"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hustmed:material:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hustmed:material:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleView(scope.row)"
            v-hasPermi="['hustmed:material:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改材料数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="!editMode">
        <el-row :gutter="1">
          <el-col :span="12">
            <el-form-item label="材料名称" prop="matName">
              <el-input readOnly=true v-model="form.matName" placeholder="请输入材料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材料编号" prop="matNo">
              <el-input v-model="form.matNo" placeholder="请输入材料编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="1">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row> 
      </el-form>
      
      <tt ref="temp" 
        :masterData="form" 
        :templateType=2 
        :templateEditable="!editMode"
        :key="form.key">
      </tt>
      
      <div slot="footer" class="dialog-footer">
        <el-button v-if="editMode" type="primary" @click="submitForm">确 定</el-button>
        <el-button v-if="editMode" @click="cancel">取 消</el-button>
        <el-button v-else @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaterial,
  getMaterial,
  delMaterial,
  addMaterial,
  updateMaterial
} from "@/api/hustmed/material";
import tt from '@/components/Template'
import searchCondition from '@/components/SearchCondition'

export default {
  name: "Material",
  dicts: ['del_flag','status','user'],
  components:{
    tt,
    searchCondition
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料数据表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        matName: null,
        matNo: null,
        vjson: null
      },
      matName:this.$route.query.matName,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        matNo: [
          { required: true, message: "材料编号不能为空", trigger: "blur" }
        ]
      },
      vjsonq:[],
      editMode:true,
      daterangeCreateTime:[]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询材料数据列表 */
    getList() {
      this.loading = true;
      this.queryParams.matName = this.matName
      this.queryParams.params = {}
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginExperimentTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endExperimentTime"] = this.daterangeCreateTime[1]
      }
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        matName: null,
        matNo: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        cjson: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.vjsonq = this.resolveVjsonQuery1()
      this.getList();
    },
    resolveVjsonQuery1(){
      if(this.vjsonq.length>0){
        let str = ''
        let reg1 = /\s+/g
        this.vjsonq.map(i=>{
          if(i.attr!='' && i.opera!='' && i.val!=''){
            str+= `CONVERT(vjson->'$."`+i.attr.replace(reg1,'')+`"',decimal(10,3)) `+i.opera+i.val +' and '
          }
        })
        return str+'1=1'
      }else{
        return ''
      }
    },
    resolveVjsonQuery2(){
      if(this.queryParams.vjson){
        let reg1 = /\s+/g
        let reg2 = /[\u4E00-\u9FA5]+/g
        let reg3 = /and/g
        let result = this.queryParams.vjson.replace(reg1,'')
          .replace(reg3,(match)=>{return ` ${match} `})
          .replace(reg2,(match)=>{ return ` CONVERT(vjson->'$."${match}"',decimal(10,3)) `})
        return result
      }else{
        return this.queryParams.vjson
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.vjsonq=[]
      this.daterangeCreateTime=[]
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.editMode =true
      this.open = true;
      this.form.matName=this.matName
      this.form.key = +new Date()
      this.title = "添加材料数据";
    },
    handleView(row){
      this.handleUpdate(row)
      this.editMode =false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.editMode =true
      const id = row.id || this.ids;
      getMaterial(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.form.key = +new Date()
        this.title = "修改材料数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.temp.save()
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              // debugger
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除材料数据编号为"' + ids + '"的数据项？')
        .then(function() {
          return delMaterial(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "hustmed/material/export",
        {
          ...this.queryParams
        },
        `material_${new Date().getTime()}.xlsx`
      );
    },
    addTemplate(){
      this.$router.push({path:'/template'})
    }
  }
};
</script>

<style lang="scss" >
.el-row {
  margin-bottom: 1px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.el-dialog__body {
    padding: 1px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
}

</style>
